package com.jcnet.bizaia.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.R.integer;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragment;
import com.baidu.cyberplayer.utils.as;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jcnet.bizaia.App;
import com.jcnet.bizaia.R;
import com.jcnet.bizaia.adapter.VodTalkAdapter;
import com.jcnet.bizaia.bean.StateBean;
import com.jcnet.bizaia.bean.VodDetailBean;
import com.jcnet.bizaia.bean.VodDetailTalkBean;
import com.jcnet.bizaia.inter_face.OnClickFullScreenListener;
import com.jcnet.bizaia.tools.JCTools;
import com.jcnet.bizaia.tools.Toolkit;
import com.jcnet.bizaia.view.ProgressHUD;
import com.jcnet.bizaia.xstream.ACache;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.Picasso;


@SuppressLint("ValidFragment")
public class VoiceTalkFragment extends SherlockFragment implements OnItemClickListener ,OnClickFullScreenListener{

	private List<VodDetailTalkBean> mainInfoBeans;

	private List<VodDetailTalkBean>tempInfoBeans;

	private PullToRefreshListView listView;

	private ListView simpleListView ;

	private View bottomView;  //底部加载更多按钮


	//private View emptyView;     //数据为空

	private View noNetWorkView;  //没有网络\


	private View firstLodingView;  //没有网络\

	private VodTalkAdapter infoAdapter;

	private int nowPageSize = 1;

	private int didNum ;

	private ACache aCache;

	private String HTTP_REQUEST =  App.HTTP_PATH+"sud_showSoundComments.action?";

	private RequestParams params;

	private int allPapeSize;


	public static final String DISCUSSIONINFOFRAGMENT_STRING = "DISCUSSIONINFOFRAGMENT_STRING" ;









	private ProgressHUD progressHUD;


	private String talkContent;
	
	private AsyncHttpClient asyncHttpClient;
	
	
	private BroadcastReceiver broadcastReceiver;
	
	public static final String TALK_CHANGE = "TALK_CHANGE";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		asyncHttpClient= new AsyncHttpClient();

		aCache = ACache.get(getActivity());

		params = new RequestParams();

		View view = View.inflate(getActivity(), R.layout.comm_list_onrefresh_with_vod_control,null);


		bottomView = View.inflate(getActivity(), R.layout.comm_foot_view, null);

		firstLodingView = View.inflate(getActivity(), R.layout.init_locad_view, null);




		

		listView = (PullToRefreshListView)view.findViewById(R.id.commListViewWitheRefresh);


		//emptyView = View.inflate(getActivity(), R.layout.list_empty_no_data, null);

		noNetWorkView = View.inflate(getActivity(), R.layout.list_no_network, null);

		initListView();
		System.out.println("onCreateView__________________");


		broadcastReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				
				System.out.println("讨论列表收到消息");
				
				
				sendTalk(
						intent.getIntExtra("didNum", -400),
						intent.getStringExtra("content")
						);
				
			}

			private void sendTalk(int didNum, String content) {
				// TODO Auto-generated method stub



				if(Toolkit.isAvaliable(getActivity())){

					if(!TextUtils.isEmpty(content.trim())){


						// TODO Auto-generated method stub
						/**
						 * 参数名称	参数类型	说明
							useridNum	int	用户编号
							didNum	int	评论对象ID
							loveNum	int	评论心情（1：喜欢2：一般3：讨厌）
							ctypeNum	int	评论类型（1：视频2：音频）
							content	string	评论内容
						 */
						RequestParams params = new RequestParams();
						params.put("useridNum", JCTools.getUserBean(getActivity()).getUserid()+"");   //需要动态
						params.put("didNum", didNum+"");    //评论对象ID
						params.put("loveNum", "2");
						params.put("ctypeNum", "2");   //固定值
						params.put("content", content);

						new AsyncHttpClient().post(App.HTTP_PATH+"comts_addComments.action?", params, new AsyncHttpResponseHandler(){
							@Override
							public void onStart() {
								// TODO Auto-generated method stub
								progressHUD = ProgressHUD.show(getActivity(), getActivity().getText(R.string.dataloding), false, true, null);
								super.onStart();
							}

							@Override
							public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
								// TODO Auto-generated method stub
								super.onSuccess(arg0, arg1, arg2);

								if(new String(arg2)!=null){
									StateBean stateBean = new Gson().fromJson(new String(arg2) , new TypeToken<StateBean>(){}.getType());
									if(stateBean.getState()==200){
										//评论成功
										talkContent = "";


										//刷新评论列表
										if(mainInfoBeans!=null){
											mainInfoBeans.clear();
										}
										nowPageSize = 1;
										sendHttp(nowPageSize);

									}else{
										//评论失败

										Toast.makeText(getActivity(), stateBean.getMessage(), 0).show();
									}
								}

							}

							@Override
							public void onFinish() {
								// TODO Auto-generated method stub
								super.onFinish();

								if(progressHUD.isShowing()){
									progressHUD.cancel();
								}
							}


							@Override
							public void onFailure(int arg0, Header[] arg1, byte[] arg2,
									Throwable arg3) {
								// TODO Auto-generated method stub
								super.onFailure(arg0, arg1, arg2, arg3);

								if(progressHUD.isShowing()){
									progressHUD.cancel();
								}
								Toast.makeText(getActivity(), getActivity().getText(R.string.serverError), 0).show();
							}
						});

					}else{
						Toast.makeText(getActivity(), getString(R.string.contentNotEmpty), 0).show();

					}

				}else{
					Toast.makeText(getActivity(), getActivity().getText(R.string.noNetWork), 0).show();

				}

			
			}
		};
		
		getActivity().registerReceiver(broadcastReceiver, new IntentFilter(TALK_CHANGE));
		
		return view;
	}

	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		getActivity().unregisterReceiver(broadcastReceiver);
	}
	
	public static VoiceTalkFragment newInstance(int didNum) {
		VoiceTalkFragment fragment = new VoiceTalkFragment();
		fragment.didNum = didNum;
		return fragment;
	}


	public VoiceTalkFragment() {
		super();
		// TODO Auto-generated constructor stub
	}





	public VoiceTalkFragment(int didNum) {
		super();
		this.didNum = didNum;
	}



	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		if(isVisibleToUser){
			System.out.println("onCreateView__________________");
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	private void initListView() {
		// TODO Auto-generated method stub

		mainInfoBeans = new ArrayList<VodDetailTalkBean>();

		tempInfoBeans = new ArrayList<VodDetailTalkBean>();


		infoAdapter = new VodTalkAdapter(getActivity(), mainInfoBeans);


		listView.setOnItemClickListener(this);


		listView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub   下拉刷新


				if(Toolkit.isAvaliable(getActivity())){
					if(mainInfoBeans!=null){
						mainInfoBeans.clear();
					}
					nowPageSize = 1;
					sendHttp(nowPageSize);
				}else{

					Toast.makeText(getActivity(), getString(R.string.noNetWork), 0).show();
					refreshView.onRefreshComplete();

				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub

			}
		});

		listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			@Override
			public void onLastItemVisible() {
				// TODO Auto-generated method stub


				if(nowPageSize==allPapeSize){
					bottomView.setVisibility(View.GONE);   //到达底部没有更多数据
					Toast.makeText(getActivity(), getString(R.string.noData), 0).show();
				}else{
					bottomView.setVisibility(View.VISIBLE);  //到达底部还有更多数据
					nowPageSize = nowPageSize+1;
					sendHttp(nowPageSize);
				}

			}
		});

		simpleListView = listView.getRefreshableView();
		simpleListView.setAdapter(infoAdapter);
		simpleListView.setOnItemClickListener(this);
		simpleListView.setEmptyView(firstLodingView);
		simpleListView.addFooterView(bottomView);
		sendHttp(nowPageSize);
		

	}

	public void sendHttp(int page){


		/**
		 * @param
		 *  参数名称	参数类型	说明
			languageNum	int	语言种类：1：中文2：英文3：日文
			vidNum	int	动画id
			pageNum	int	当前第几页（默认第一页）——评论表
			pageSizeNum	int	当前分页显示条数（默认20条）——评论条数
		 */
		params.put("languageNum", App.localeCode+"");
		params.put("sidNum", didNum+"");     	// 需要动态
		params.put("pageNum", page+"");
		//params.put("pageSizeNum",20);

		System.out.println("哇哈哈 我是评论列表");

		if(Toolkit.isAvaliable(getActivity())){

			asyncHttpClient.post(HTTP_REQUEST,params ,new AsyncHttpResponseHandler(){

				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					super.onStart();

				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub\

					super.onSuccess(arg0, arg1, arg2);

					if(new String(arg2)!=null){

						aCache.put(HTTP_REQUEST+params, new String(arg2),App.CACHE_TIME_DAY);
						setListData(new String(arg2));
					}


				}


				@Override
				public void onFinish() {
					// TODO Auto-generated method stub
					super.onFinish();
					if(listView.isRefreshing()){
						listView.onRefreshComplete();
					}
					bottomView.setVisibility(View.GONE);


				}

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					Toast.makeText(getActivity(), getString(R.string.serverError), 0).show();
					super.onFailure(arg0, arg1, arg2, arg3);
				}
			});
		}else{
			if(listView.isRefreshing()){
				listView.onRefreshComplete();
			}

			simpleListView.setEmptyView(noNetWorkView);


			firstLodingView.setVisibility(View.GONE);

			String requestString = aCache.getAsJSONObject(HTTP_REQUEST+params).toString();

			if(requestString!=null){

				setListData(requestString);
			}


			Toast.makeText(getActivity(), getString(R.string.noNetWork), 1).show();

		}
	}


	private void setListData(String arg2){



		String requestString = arg2;

		AllVoidDetial requestBeanRequest = new AllVoidDetial();


		//System.out.println("byte:"+new String(arg2));

		if(requestString!=null){

			System.out.println("requestString="+requestString);

			requestBeanRequest = new Gson().fromJson(requestString, new TypeToken<AllVoidDetial>(){}.getType());


			if(requestBeanRequest.getState()==200){
				
				firstLodingView.setVisibility(View.GONE);

				tempInfoBeans = null;
				tempInfoBeans = requestBeanRequest.getObjlistJson();

				if(!tempInfoBeans.isEmpty()||tempInfoBeans!=null){
					allPapeSize = requestBeanRequest.getPagsum();
					if(tempInfoBeans.isEmpty()||mainInfoBeans.size()<20){   //当本页的

						bottomView.setVisibility(View.GONE);

					}

					if(!tempInfoBeans.isEmpty()){

						mainInfoBeans.addAll(tempInfoBeans);

						infoAdapter.count = mainInfoBeans.size();

						infoAdapter.notifyDataSetChanged();
					}
				}


				//如果得到的内容总数为空的话显示没有数据的页面,同时隐藏foot界面
				if(mainInfoBeans.isEmpty()){
					//simpleListView.setEmptyView(emptyView);
					bottomView.setVisibility(View.GONE);
				}


			}else{
				Toast.makeText(getActivity(), requestBeanRequest.getMessage(), 0).show();
			}

			listView.onRefreshComplete();
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		/*Intent intent = new Intent(getActivity(), DiscussDetialActivity.class);
		intent.putExtra("imgUrl", mainInfoBeans.get(arg2).getPictureurl());
		startActivity(intent);*/
	}


	class AllVoidDetial {
		private int state;
		private String message;
		private int pagsum;
		private  List<VodDetailTalkBean> objlistJson;
		public int getState() {
			return state;
		}
		public void setState(int state) {
			this.state = state;
		}
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		public int getPagsum() {
			return pagsum;
		}
		public void setPagsum(int pagsum) {
			this.pagsum = pagsum;
		}
		public List<VodDetailTalkBean> getObjlistJson() {
			return objlistJson;
		}
		public void setObjlistJson(List<VodDetailTalkBean> objlistJson) {
			this.objlistJson = objlistJson;
		}


	}


	@Override
	public void onClick(ImageButton imageButton) {
		// TODO Auto-generated method stub

	}
}
